package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.PublicConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserCollect;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserCollectVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.common.util.StringUtils;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RsaSigner rsaSigner;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Override
    public Map<String, Object> WxLogin(String code) {
        String openid = "";

        //判断code是否存在
        if (StringUtils.isEmpty(code)) {
            throw new GuiguException(201, "code码不存在");
        }

        //调用微信服务端
        WxMaUserService userService = wxMaService.getUserService();
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            sessionInfo = userService.getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            log.error("调用微信服务端失败:{}", e.getMessage());
            throw new GuiguException(201, "调用微信服务端失败");
        }

        String refreshTokenKey = RedisConstant.USER_LOGIN_REFRESH_KEY_PREFIX + openid;
        String jsonWebTokenFromRedis = redisTemplate.opsForValue().get(refreshTokenKey);
        if (!org.springframework.util.StringUtils.isEmpty(jsonWebTokenFromRedis)) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("token", jsonWebTokenFromRedis);
            return map1;
        }

        //根据openId查询用户信息
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getWxOpenId, openid);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        //当数据库中不存在这个用户时 创建一个新用户
        if (userInfo == null) {
            // 1.像user_info表中插入用户（注册用户信息）
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname(System.currentTimeMillis() + "-【hzk】-" + UUID.randomUUID().toString().substring(0, 4).replace("-", ""));  // 昵称
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setIsVip(0);  // 不是vip
            userInfo.setVipExpireTime(new Date());
            int insert = userInfoMapper.insert(userInfo);
            log.info("注册用户：{}", insert > 0 ? "success" : "fail");
            //  像tingshu_account库中的user_account表中插入用户账户（初始化用户账户余额）
            rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_REGISTER, userInfo.getId().toString());
            log.info("用户微服务发送初始化用户账户余额消息：{}成功!",userInfo.getId());

        }

        //得到jsonWebToken
        String token = getJsonWebToken(openid, userInfo.getId());

        //将jsonWebToken存在Redis中
        String accessTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + openid;
        redisTemplate.opsForValue().set(accessTokenKey, token, 20, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(refreshTokenKey, token, 180, TimeUnit.DAYS);

        //返回
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token", token); // token值
        return map;
    }

    @Override
    public Map<String, Object> getNewAccessToken() {

        HashMap<String, Object> result = new HashMap<>();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 1.2 获取请求对象
        HttpServletRequest request = requestAttributes.getRequest();
        // 1.3 获取请求对象的请求头
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new GuiguException(201, "之前没有登录过");
        }

        // 2.校验jsonWebToken是否被篡改了。
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(PublicConstant.PUBLIC_KEY));
        String claims = jwt.getClaims();
        Map map = JSONObject.parseObject(claims, Map.class);
        Object openId = map.get("openId");
        Object userId = map.get("id");


        String refreshTokenKey = RedisConstant.USER_LOGIN_REFRESH_KEY_PREFIX + openId;
        String accessTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + openId;


        // 1.从Redis中获取RefreshToken
        String refreshToken = redisTemplate.opsForValue().get(refreshTokenKey);
        if (!org.springframework.util.StringUtils.isEmpty(refreshToken)) {
            String jsonWebToken = getJsonWebToken(String.valueOf(openId.toString()), Long.parseLong(userId.toString()));
            redisTemplate.opsForValue().set(accessTokenKey, jsonWebToken, 20, TimeUnit.DAYS);
            redisTemplate.opsForValue().set(refreshTokenKey, jsonWebToken, 180, TimeUnit.DAYS);
            result.put("token", jsonWebToken);
            return result;

        } else {
            // 去登录
            result.put("1", "v");
        }

        return result;
    }

    @Override
    public void updateUser(UserInfoVo userInfoVo) {
        // 1.查询用户信息
        Long userId = AuthContextHolder.getUserId();

        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (null == userInfo) {
            throw new GuiguException(201, "用户信息不存在");
        }
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfoVo getUserInfo(Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);

        if (userInfo == null) {
            throw new GuiguException(201, "用户不存在");
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);

        return userInfoVo;
    }

    @Override
    public Map<Long, String> getUserPaidAlbumTrack(Long userId, Long albumId) {

        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidTrack::getUserId, userId);
        wrapper.eq(UserPaidTrack::getAlbumId, albumId);
        List<UserPaidTrack> userPaidTracks = userPaidTrackMapper.selectList(wrapper);

        Map<Long, String> map = userPaidTracks
                .stream()
                .collect(Collectors
                        .toMap(
                                UserPaidTrack::getTrackId, v -> "1"
                        )
                );
        return map;
    }

    @Override
    public Boolean getUserPaidAlbum(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidAlbum> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidAlbum::getUserId, userId);
        wrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(wrapper);
        return userPaidAlbum != null;
    }

    @Override
    public Boolean collect(Long trackId) {
        Long userId = AuthContextHolder.getUserId();

        // 1.构建条件对象
        Criteria criteria = Criteria.where("userId").is(userId).and("trackId").is(trackId);

        // 2.构建查询对象
        Query query = new Query(criteria);

        // 3.开始查询
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId);
        UserCollect userCollect = mongoTemplate.findOne(query, UserCollect.class, collectionName);
        if (userCollect == null) {
            // 收藏声音
            // 插入收藏对象到MongoDB
            userCollect = new UserCollect();
            userCollect.setId(ObjectId.get().toString());
            userCollect.setUserId(userId);
            userCollect.setTrackId(trackId);
            userCollect.setCreateTime(new Date());
            mongoTemplate.save(userCollect, collectionName);
            TrackStatMqVo trackStatMqVo = prepareTrackStatMqDto(null, userCollect.getTrackId(), SystemConstant.TRACK_STAT_COLLECT, 1);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSONObject.toJSONString(trackStatMqVo));

            return true;  // 收藏过
        } else {
            // 取消收藏
            mongoTemplate.remove(query, UserCollect.class, collectionName);
            TrackStatMqVo trackStatMqVo = prepareTrackStatMqDto(null, userCollect.getTrackId(), SystemConstant.TRACK_STAT_COLLECT, -1);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSONObject.toJSONString(trackStatMqVo));
            return false;

        }
    }

    @Override
    public TrackStatMqVo prepareTrackStatMqDto(Long albumId, Long trackId, String trackStatType, int count) {
        TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
        trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replace("-", "")); // 消息去重
        trackStatMqVo.setAlbumId(albumId);
        trackStatMqVo.setTrackId(trackId);
        trackStatMqVo.setStatType(trackStatType);
        trackStatMqVo.setCount(count);
        return trackStatMqVo;
    }

    @Override
    public Boolean isCollect(Long trackId) {
        Long userId = AuthContextHolder.getUserId();
        Criteria criteria = Criteria.where("userId").is(userId).and("trackId").is(trackId);
        Query query = new Query(criteria);
        long count = mongoTemplate.count(query, UserCollect.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId));
        return count > 0;
    }

    @Override
    public IPage<UserCollectVo> findUserCollectPage(IPage<UserCollectVo> pageParam) {

        Long userId = AuthContextHolder.getUserId();
        // 1.构建条件对象
        Criteria criteria = Criteria.where("userId").is(userId);

        // 2.构建查询对象
        Query query = new Query(criteria);

        // 3.构建分页和排序条件对象【mp中分页查询对MySQL查询有效】

        Sort sort = Sort.by(Sort.Order.desc("createTime"));
        // from:(pn-1)*size   size
        PageRequest pageAndSort = PageRequest.of((int) ((pageParam.getCurrent() - 1) * pageParam.getSize()), (int) pageParam.getSize(), sort);
        query.with(pageAndSort);

        // 4.查询总记录数
        long count = mongoTemplate.count(query.limit(-1), UserCollect.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId));


        // 5.查询数据
        List<UserCollect> userCollectList = mongoTemplate.find(query, UserCollect.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId));

        List<Long> trackIdList = userCollectList.stream().map(UserCollect::getTrackId).collect(Collectors.toList());
        // 6.根据声音id集合 查询【声音对象】集合
        Result<List<TrackListVo>> trackListVoResult = albumInfoFeignClient.getTrackListByIds(trackIdList);
        List<TrackListVo> trackListVos = trackListVoResult.getData();
        if (CollectionUtils.isEmpty(trackListVos)) {
            throw new GuiguException(201, "远程查询专辑微服务获取声音集合失败");
        }

        //  7.将声音对象的列表集合转成声音对象的Map集合
        Map<Long, TrackListVo> trackListVoMap = trackListVos.stream().collect(Collectors.toMap(TrackListVo::getTrackId, v -> v));


        List<UserCollectVo> userCollectVoList = userCollectList.stream().map(userCollect -> {
            UserCollectVo userCollectVo = new UserCollectVo();
            TrackListVo trackListVo = trackListVoMap.get(userCollect.getTrackId());
            userCollectVo.setAlbumId(trackListVo.getAlbumId());// 收藏声音对应的专辑id
            userCollectVo.setTrackId(userCollect.getTrackId());
            userCollectVo.setCreateTime(userCollect.getCreateTime());
            userCollectVo.setTrackTitle(trackListVo.getTrackTitle());  // 收藏声音标题
            userCollectVo.setCoverUrl(trackListVo.getCoverUrl());  // 收藏声音的封面
            return userCollectVo;
        }).collect(Collectors.toList());
        return pageParam.setRecords(userCollectVoList).setTotal(count);
    }

    private String getJsonWebToken(String openid, Long userId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", userId);
        jsonObject.put("openId", openid);
        // jwt方式生成
        Jwt jwt = JwtHelper.encode(jsonObject.toString(), rsaSigner);

        String encoded = jwt.getEncoded();
        return encoded;
    }


}
